package com.gsafety.libraryktx.util

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.os.Process
import android.os.StrictMode
import android.text.TextUtils
import android.util.Base64
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.ActivityUtils
import com.gsafety.library.Widgets.dia.OnSweetClickListener
import com.gsafety.library.Widgets.dia.SweetAlertDia
import com.gsafety.libraryktx.config.Constant
import com.gsafety.libraryktx.manager.UserManager
import com.jeremyliao.liveeventbus.LiveEventBus
import java.io.File
import java.net.URL
import java.net.URLEncoder
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess

/**
 * app内容使用的工具方法类
 */
object AppUtil {
    fun getYmd(date: Date?): String {
        if (date != null) {
            try {
                val sf = SimpleDateFormat("yyyy-MM-dd")
                return sf.format(date)
            } catch (e: Exception) {
            }
        }
        return ""
    }

    fun getY(date: Date?): String {
        if (date != null) {
            try {
                val sf = SimpleDateFormat("yyyy")
                return sf.format(date)
            } catch (e: Exception) {
            }
        }
        return ""
    }

    fun getYmdhmss(date: Date): String {
        if (date != null) {
            try {
                val sf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                return sf.format(date)
            } catch (e: Exception) {
            }
        }
        return ""
    }

    fun getYmdhm(date: Date): String {
        if (date != null) {
            try {
                val sf = SimpleDateFormat("yyyy-MM-dd HH:mm")
                return sf.format(date)
            } catch (e: Exception) {
            }
        }
        return ""
    }

    fun getHmss(date: Date): String {
        if (date != null) {
            try {
                val sf = SimpleDateFormat("HH:mm:ss")
                return sf.format(date)
            } catch (e: Exception) {
            }
        }
        return ""
    }

    fun getHmssSSS(date: Date): String {
        if (date != null) {
            try {
                val sf = SimpleDateFormat("HH:mm:ss:SSS")
                return sf.format(date)
            } catch (e: Exception) {
            }
        }
        return ""
    }

    fun getYmdHmssSSS(date: Date): String {
        if (date != null) {
            try {
                val sf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
                return sf.format(date)
            } catch (e: Exception) {
            }
        }
        return ""
    }

    fun getYmdHmss(date: Date): String {
        if (date != null) {
            try {
                val sf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                return sf.format(date)
            } catch (e: Exception) {
            }
        }
        return ""
    }

    fun formatHms(time: String): String {
        if (time != null) {
            try {
                val sf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                val date = sf.parse(time)
                return getHmss(date)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return ""
    }

    fun getTimeMil(time: String?): Long {
        if (time != null) {
            try {
                val sf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                val date = sf.parse(time)
                return date.time
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return 0
    }

    fun getFormatDateYYYYHHmmss(time: String?):Date{
        if (time != null) {
            try {
                val sf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                val date = sf.parse(time)
                return date
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return Date()
    }



    /**
     * 动态显示软键盘
     *
     * @param activity The activity.
     */
    fun showSoftInput(activity: Activity) {
        val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
                ?: return
        var view = activity.currentFocus
        if (view == null) view = View(activity)
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED)
    }

    /**
     * 动态显示软键盘
     *
     * @param view 视图
     */
    fun showSoftInput(context: Context, view: View) {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                ?: return
        view.isFocusable = true
        view.isFocusableInTouchMode = true
        view.requestFocus()
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED)
    }

    /**
     * 动态隐藏软键盘
     *
     * @param activity The activity.
     */
    fun hideSoftInput(activity: Activity) {
        val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
                ?: return
        var view = activity.currentFocus
        if (view == null) view = View(activity)
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    /**
     * 动态隐藏软键盘
     *
     * @param view 视图
     */
    fun hideSoftInput(context: Context, view: View) {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                ?: return
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }






    private fun getFileType(filePath: String): String {
        var type = "*/*"
        val file = File(filePath)
        if (file.exists()) {
            /* 取得扩展名 */
            val end = file.name.substring(file.name.lastIndexOf(".") + 1, file.name.length).toLowerCase(Locale.getDefault())
            if (end == "m4a" || end == "mp3" || end == "mid" || end == "xmf" || end == "ogg" || end == "wav") {
                type = "audio/*"
            } else if (end == "3gp" || end == "mp4") {
                type = "video/*"
            } else if (end == "jpg" || end == "gif" || end == "png" || end == "jpeg" || end == "bmp") {
                type = "image/*"
            } else if (end == "apk") {
                type = "application/vnd.android.package-archive"
            } else if (end == "ppt" || end == "pptx") {
                type = "application/vnd.ms-powerpoint"
            } else if (end == "xls" || end == "xlsx") {
                type = "application/vnd.ms-excel"
            } else if (end == "doc" || end == "docx") {
                type = "application/msword"
            } else if (end == "pdf") {
                type = "application/pdf"
            } else if (end == "chm") {
                type = "application/x-chm"
            } else if (end == "txt") {
                type = "text/plain"
            }
        }
        return type
    }

    fun openFileByType(context: Context, filePath: String) {
        val intent = Intent();
        // 这是比较流氓的方法，绕过7.0的文件权限检查
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val builder = StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
        val file = File(filePath);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.action = Intent.ACTION_VIEW;//动作，查看
        intent.setDataAndType(Uri.fromFile(file), getFileType(filePath));//设置类型
        context.startActivity(intent);
    }

    fun isNeedFile(path: String?): Boolean {
        if (path.isNullOrEmpty()) {
            return false
        } else {
            val file = File(path)
            if (file.exists()) {
                /* 取得扩展名 */
                val type = file.name.substring(file.name.lastIndexOf(".") + 1, file.name.length).toLowerCase(Locale.getDefault())
                return type == "pdf" || type == "doc" || type == "xls" || type == "xlsx" || type == "docx"
            }
            return false
        }
    }

    fun getVersionName(context: Context?): String {
        try {
            if (context != null) {
                val packageInfo = context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_CONFIGURATIONS)
                return packageInfo.versionName
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    fun getVersionCode(context: Context?): Int {
        try {
            if (context != null) {
                val packageInfo = context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_CONFIGURATIONS)
                return packageInfo.versionCode
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }



    fun base64Encoder(str: String): String {
        var encode = Base64.encodeToString(str.toByteArray(), Base64.NO_WRAP)
        return encode
    }




    /**
     * 判断是否是office文件
     */
    fun isoffice(lastStr: String): Boolean {
        var office = false
        if (!TextUtils.isEmpty(lastStr)) {
            var index: Int? = lastStr?.lastIndexOf(".")
            if (-1 != index) {
                var name = lastStr?.substring(index!! + 1)
                when (name) {
                    "doc" -> {
                        office = true
                    }
                    "xls" -> {
                        office = true
                    }
                    "xlsx" -> {
                        office = true
                    }
                    "pdf" -> {
                        office = true
                    }
                    "docx"->{
                        office = true
                    }
                }
            }
        }
        return office
    }

    fun showConfirmDia(ctx: Context, title: String?, content: String, confirmTxt: String?, cancelTxt: String?, confirmListener: OnSweetClickListener, cancelListener: OnSweetClickListener, showCancelBtn: Boolean, cancelable: Boolean) {
        val dia = SweetAlertDia(ctx, cancelable)
        dia.show()
        dia.setTitleText(title).setContentText(content).setCancelText(cancelTxt).setConfirmText(confirmTxt).setCancelListener(cancelListener).setConfirmListener(confirmListener).showCancelButton(showCancelBtn)
    }

    fun showConfirmDia(ctx: Context, content: String, confirmListener: OnSweetClickListener, cancelListener: OnSweetClickListener, showCancelBtn: Boolean) {
        showConfirmDia(ctx, null, content, null, null, confirmListener, cancelListener, showCancelBtn, true)
    }

    /**
     * 退出登录
     */
    fun exitLogin() {
        if (UserManager.getInstance().getUser() != null) {
            LiveEventBus.get(Constant.EventBus_KEY_LOGINOUT).post("")
        }
    }
    /**
     * 退出应用程序
     *
     */
    @SuppressLint("CheckResult")
    fun appExit() {
        ActivityUtils.finishAllActivities()
    }
}